<?php
/**
 * 获取请求客户端的IP地址
 * @return string 请求客户端的IP地址
 */
function get_client_ip()
{
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    }
    else if( isset($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else if(isset($_SERVER['HTTP_X_FORWARDED'])) {
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    }
    else if(isset($_SERVER['HTTP_FORWARDED_FOR'])) {
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    }
    else if(isset($_SERVER['HTTP_FORWARDED'])){
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    }
    else if(isset($_SERVER['REMOTE_ADDR'])) {
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    }

    if (strpos($ipaddress, ',') !== false) {
        $ips = explode(',', $ipaddress);
        $ipaddress = trim($ips[0]);
    }
    if ($ipaddress == '::1') {
        $ipaddress = '';
    }
    return $ipaddress;
}

// 获取服务器的链接地址
function getServerURL()
{
    $url = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on")? "https://" : "http://";
    // $_SERVER["HTTP_HOST"] is equivalent
    $url .= $_SERVER["SERVER_NAME"];
    if ($_SERVER["SERVER_PORT"] != "80") {
        $url .= ":".$_SERVER["SERVER_PORT"];
    }
    return $url;
}

// 获取完整的URL链接
function getCompleteURL()
{
    return getServerURL().$_SERVER["REQUEST_URI"];
}

// 获取服务器的根目录
function getDocumentRoot()
{
    $val = "";
    if ( isset($_SERVER['DOCUMENT_ROOT']) ) {
        $val = $_SERVER['DOCUMENT_ROOT'];
    }
    if ( strlen($val) == 0 ) {
        if ( isset($_SERVER['SCRIPT_FILENAME']) ) {
            $path = $_SERVER['SCRIPT_FILENAME'];
        }
        else if ( isset($_SERVER['PATH_TRANSLATED']) ) {
            $path = str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED']);
        }
        $val = str_replace( '\\', '/', substr($path, 0, 0-strlen($_SERVER['PHP_SELF'])));
    }

    // 该代码的作用有待进一步确认
    //$doc_root = str_replace('//','/',str_replace(DIRECTORY_SEPARATOR,'/',$_SERVER["DOCUMENT_ROOT"]));

    return $val;
}

